package javabase.concurrent;





public class ThreadCreationCmp {

    static class Counter {
        private int count = 0;
        public void increment() {
            count++;
        }
        public int value() {
            return count;
        }
    }


    /**
     * 这种方式意味着多个线程实例可以共享同一个Runnable实例。
     * 创建一个线程实例成本要比创建一个Runnable实例昂贵一点。
     */
    static class CountingTask implements Runnable {

        private Counter counter = new Counter();

        @Override
        public void run() {
            for (int i=0; i<100; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                counter.increment();
            }
            System.out.println("CountingTask : " + counter.value());
        }
    }


    static class CountingThread extends Thread {

        private Counter counter = new Counter();

        @Override
        public void run() {
            for (int i=0; i<100; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                counter.increment();
            }
            System.out.println("CountingThread : " + counter.value());
        }
    }

    public static void main(String[] args) {
        Thread t;
        CountingTask ct = new CountingTask();

        final int numberOfProcessors = Runtime.getRuntime().availableProcessors();

        for (int i=0; i<2*numberOfProcessors; i++) {
            t = new Thread(ct);
            t.start();
        }

        for (int i=0; i<2*numberOfProcessors; i++) {
            t = new CountingThread();
            t.start();
        }

    }

}
